package fenyu.personblob.web.util;

import com.google.gson.Gson;
import fenyu.personblob.bean.databean.User;
import fenyu.personblob.bean.strategy.Strategy;
import fenyu.personblob.single.SinglePathDoor;
import org.apache.commons.codec.binary.Base64;


import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * create at 2018/12/22 9:10
 *
 * @author 纷羽 <gzj0078@gmail.com>
 */
public class TokenMakerStrategy implements Strategy {

    private static String data = "abcdefghijklmnopqrstuvwxyz1234567890";

    /**
     * 生成token
     *
     * @param args
     * @return
     */
    @Override
    public Object todo(Object... args) {
        User user = (User) args[0];
        String key = random(5);
        user.setToken(key);
        SinglePathDoor.getSingleSave().getSaveDoor().getUserSavePath().save(user);
        Gson gson = new Gson();
        TokenSave tokenSave = new TokenSave();
        tokenSave.setId(user.getId());
        tokenSave.setKey(key);
        try {
            return Base64.encodeBase64String(rsaCreate(gson.toJson(tokenSave)));
        } catch (Exception e) {
         throw new UnknownError();
        }
    }

    private String random(int length) {
        String chara = data.charAt((int) (Math.random() * data.length())) + "";
        if (length != 1)
            return chara + random(length - 1);
        else return chara;
    }

    private byte[] rsaCreate(String data) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, SinglePathDoor.getSingleSave().getSaveDoor().getKEY_PAIR().getPublic());
        return cipher.doFinal(data.getBytes());
    }
}
